package com.jy.adscm.zltx.controller;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.support.SimpleCoreResponse;
import com.jy.adscm.system.utils.AdscmSystemUtils;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.zltx.bean.*;
import com.jy.adscm.zltx.service.JyDrawingAnnexService;
import com.jy.adscm.zltx.service.JyDrawingEditInfoService;
import com.jy.adscm.zltx.service.JyDrawingListService;
import com.jy.adscm.zltx.service.JyDrawingRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 图纸清单表 前端控制器
 * </p>
 *
 * @author zyl
 * @since 2018-10-26
 */
@RestController
@RequestMapping("/adscm/zltx/jyDrawingList")
public class JyDrawingListController {


    @Value("${zltx.drawing.upload.formal-upload-path}")
    private  String formalUploadPath;
    @Value("${zltx.drawing.upload.history-upload-path}")
    private  String historyUploadPath;
    @Value("${zltx.drawing.upload.annex-upload-path}")
    private  String annexUploadPath;//附件上传路径

    @Autowired
    RedisTemplate<Object, Token> tokenRedisTemplate;

    @Autowired
    JyDrawingListService jyDrawingListService;
    @Autowired
    JyDrawingAnnexService jyDrawingAnnexService;
    @Autowired
    JyDrawingEditInfoService jyDrawingEditInfoService;
    @Autowired
    JyDrawingRelationService  jyDrawingRelationService;

    private void loadDrawingList(JyDrawingList jyDrawingList, HttpServletRequest request) throws AdscmSystemException {
        List<String> paths = null;

        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            paths = AdscmSystemUtils.getInstance().uploadFile(multiRequest,formalUploadPath);
        }
        if (paths != null && paths.size()>0){
            String drawingPath = paths.get(0);
            drawingPath = drawingPath.substring(drawingPath.lastIndexOf("\\") + 1);
            jyDrawingList.setDrawingPath(drawingPath);
        }
//        if (paths != null && paths.size()>1){
//            String instructionsPath = paths.get(1);
//            instructionsPath = instructionsPath.substring(instructionsPath.lastIndexOf("\\") + 1);
//            jyDrawingList.setInstructionsPath(instructionsPath);
//        }
    }

    @RequestMapping("/insert")
    public SimpleCoreResponse insert(JyDrawingList jyDrawingList, HttpServletRequest request) throws AdscmSystemException{

        this.loadDrawingList(jyDrawingList,request);

        return new SimpleCoreResponse("200","新增成功" ,jyDrawingListService.insert(jyDrawingList));
    }
    @RequestMapping("/auditingDrawing")
    public SimpleCoreResponse auditingDrawing(String jyDrawingStr, HttpServletRequest request) throws AdscmSystemException, IOException{

        ObjectMapper mapper = new ObjectMapper();
        Date now = new Date();
        JyDrawingList jyDrawingList = mapper.readValue(jyDrawingStr,JyDrawingList.class);

        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
//        jyDrawingList.setDrawingAuditor(token.getUser().getId());
//        jyDrawingList.setDrawingAuditTime(now);
        jyDrawingListService.updateJyDrawing(Integer.valueOf(String.valueOf(jyDrawingList.getId())));
        return new SimpleCoreResponse("200","审核成功" ,jyDrawingListService.updateById(jyDrawingList));
    }
    @RequestMapping("/update")
    public SimpleCoreResponse update(@RequestBody JyDrawingList jyDrawingList /*String jyDrawingStr*/, HttpServletRequest request) throws AdscmSystemException, IOException{

//        ObjectMapper mapper = new ObjectMapper();
        Date now = new Date();
//        JyDrawingList jyDrawingList = mapper.readValue(jyDrawingStr,JyDrawingList.class);
        jyDrawingList.setAddFlag("1");
        jyDrawingList.setCreateTime(now);

        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        jyDrawingList.setDrawingCreater(token.getUser().getId());
        jyDrawingList.setLastEditTime(now);
        jyDrawingList.setChangeTimes(0);
        jyDrawingListService.updateJyDrawing(Integer.valueOf(String.valueOf(jyDrawingList.getId())));
        //        this.loadDrawingList(jyDrawingList,request);



        Wrapper<JyDrawingRelation> jyDrawingRelationWrapper=new EntityWrapper<>();
        jyDrawingRelationWrapper.eq("relation_id",jyDrawingList.getId());
        List<JyDrawingRelation> jyDrawingRelations = jyDrawingRelationService.selectList(jyDrawingRelationWrapper);
        if (jyDrawingRelations.size()>0){
            JyDrawingRelation relation = jyDrawingRelations.get(0);
            Integer drawingId = relation.getDrawingId();
            Wrapper<JyDrawingRelation> jyDrawingRelationWrapper1=new EntityWrapper<>();
            jyDrawingRelationWrapper1.eq("drawing_id",drawingId);
            List<JyDrawingRelation> jyDrawingRelations1 = jyDrawingRelationService.selectList(jyDrawingRelationWrapper1);
            for (JyDrawingRelation jyDrawingRelation : jyDrawingRelations1) {
                JyDrawingList jyDrawingListRelation = jyDrawingListService.selectById(Long.valueOf(jyDrawingRelation.getRelationId()));
                jyDrawingListRelation.setDrawingPath(jyDrawingList.getDrawingPath());
                jyDrawingListService.updateById(jyDrawingListRelation);
            }
        }



        return new SimpleCoreResponse("200","修改成功" ,jyDrawingListService.updateById(jyDrawingList));
    }

    @RequestMapping("/delete/{id}")
    public SimpleCoreResponse update(@PathVariable Integer id, HttpServletRequest request){
        return new SimpleCoreResponse("200","删除成功" ,jyDrawingListService.deleteById(id));
    }
    @RequestMapping("/selectById/{id}")
    public SimpleCoreResponse selectById(@PathVariable Integer id, HttpServletRequest request) throws AdscmSystemException{
        JyDrawingList jyDrawingList = jyDrawingListService.selectJyDrawingById(id);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }
    @RequestMapping("/selectRelationDraw/{id}")
    public SimpleCoreResponse selectRelationDraw(@PathVariable Integer id, HttpServletRequest request) throws AdscmSystemException{
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectRelationDraw(id);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }
    @RequestMapping("/selectRelation/{id}")
    public SimpleCoreResponse selectRelation(@PathVariable Integer id, HttpServletRequest request) throws AdscmSystemException{
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectRelation(id);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }
    @RequestMapping("/selectAll")
    public SimpleCoreResponse selectAll(HttpServletRequest request) throws AdscmSystemException {
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingListService.selectAllByFilter(token));
    }

    /**
     * 上传图纸或者说明书
     * @param type 类型：1 表示上传正式图纸，2 表示修改记录的上传图纸
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/uploadDrawing/{type}")
    public SimpleCoreResponse uploadDrawing(@PathVariable Integer type,HttpServletRequest request) throws AdscmSystemException {

        List<String> paths = null;

        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            String path = "";
            if (type == 1){
                path = formalUploadPath;
            }else {
                path = historyUploadPath;
            }

            paths = AdscmSystemUtils.getInstance().uploadFile(multiRequest,path);
        }
        String drawingPath = null;
        if (paths != null && paths.size()>0){
            drawingPath = paths.get(0);

            drawingPath = drawingPath.substring(drawingPath.lastIndexOf("\\") + 1);
        }

//        String[] drawingPath = new String[2];
//        if (paths != null && paths.size()>0){
//            drawingPath[0] = paths.get(0);
//            drawingPath[0] = drawingPath[0].substring(drawingPath[0].lastIndexOf("\\") + 1);
//        }
//        if (paths != null && paths.size()>1){
//            drawingPath[1] = paths.get(1);
//            drawingPath[1] = drawingPath[1].substring(drawingPath[1].lastIndexOf("\\") + 1);
//        }

        return new SimpleCoreResponse("200","上传成功" ,drawingPath);
    }
    /**
     * 上传图纸关联的附件
     * @param id 图纸ID
     * @param type 类型：1 表示上传正式图纸附件，2 表示修改记录的上传图纸附件
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/uploadAnnex/{id}/{type}")
    public SimpleCoreResponse uploadAnnex(@PathVariable Long id,@PathVariable Integer type,HttpServletRequest request) throws AdscmSystemException {

        List<String> paths = null;

        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            String path = annexUploadPath + id + File.separator + UUID.randomUUID().toString().replaceAll("-","") + File.separator;

            paths = AdscmSystemUtils.getInstance().uploadFileNoNewName(multiRequest,path);
        }
        if (paths != null){
            for (String path : paths) {

                JyDrawingAnnex annex = new JyDrawingAnnex();
                annex.setDrawingId(id);
                annex.setAnnexPath(path);
                annex.setAnnexType(type);

                jyDrawingAnnexService.insert(annex);
            }
        }


        return new SimpleCoreResponse("200","上传成功" ,paths);
    }

    /**
     * 查询图纸PDF
     * @param id
     * @param type 类型：1：获取正式图纸，2：获取正式说明书，3：获取历史某个版本图纸，4：获取历史某个版本说明书
     * @param response
     * @throws AdscmSystemException
     */
    @RequestMapping("/viewDrawingPdf/{id}/{type}")
    public void viewPdf(@PathVariable Integer id,@PathVariable Integer type, HttpServletResponse response) throws AdscmSystemException {

        String filePath = null;
        switch (type){
            case 1 :
                JyDrawingList jyDrawingList = jyDrawingListService.selectById(id);
                filePath = formalUploadPath + File.separator + jyDrawingList.getDrawingPath();
                break;
            case 2 :
//                jyDrawingList = jyDrawingListService.selectById(id);
//                filePath = formalUploadPath + File.separator + jyDrawingList.getInstructionsPath();
                break;
            case 3 :
                JyDrawingEditInfo jyDrawingEditInfo = jyDrawingEditInfoService.selectById(id);
                filePath = historyUploadPath + File.separator + jyDrawingEditInfo.getModifiedDrawingPath();
                break;
            case 4 :
//                jyDrawingEditInfo = jyDrawingEditInfoService.selectById(id);
//                filePath = historyUploadPath + File.separator + jyDrawingEditInfo.getModifiedInstructionsPath();
                break;
        }

        AdscmSystemUtils.getInstance().writeFile(filePath,response);
    }

    /**
     * 下载PDF
     * @param id
     * @param type 类型：1：获取正式图纸，2：获取历史某个版本图纸
     * @param response
     */
    @RequestMapping("/downloadPdf/{id}/{type}")
    public void downloadPdf(@PathVariable Integer id,@PathVariable Integer type, HttpServletResponse response) throws AdscmSystemException {

        String fileName = null;
        if(type == 1){
            JyDrawingList jyDrawingList = jyDrawingListService.selectById(id);
            fileName = formalUploadPath + jyDrawingList.getDrawingPath();
        }else {
            //历史版本
            JyDrawingEditInfo jyDrawingEditInfo = jyDrawingEditInfoService.selectById(id);
            fileName = historyUploadPath + jyDrawingEditInfo.getModifiedDrawingPath();
        }
        AdscmSystemUtils.getInstance().downloadFile(fileName,response);
    }

    /**
     * 下载文件
//     * @param fileName
     * @param response
     */
    @RequestMapping("/downloadFile/{id}")
    public void downloadFile(@PathVariable Integer id,HttpServletResponse response) throws AdscmSystemException {

        JyDrawingAnnex jyDrawingAnnex = jyDrawingAnnexService.selectById(id);
        String fileName = jyDrawingAnnex.getAnnexPath();

        AdscmSystemUtils.getInstance().downloadFile(fileName,response);

    }
    @RequestMapping("/selectByParentId/{id}")
    public SimpleCoreResponse selectByParentId(@PathVariable Integer id, HttpServletRequest request) throws AdscmSystemException{
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectByParentId(id,token);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }
    @RequestMapping("/selectByDrawType/{id}")
    public SimpleCoreResponse selectByDrawType(@PathVariable Integer id, HttpServletRequest request) throws AdscmSystemException{
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectByDrawType(id,token);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }

    @RequestMapping("/selectByKeyWords")
    public SimpleCoreResponse selectByKeyWords( String  keyWords, HttpServletRequest request) throws AdscmSystemException{
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectByKeyWords(keyWords);
        return new SimpleCoreResponse("200","查询成功" ,jyDrawingList);
    }

    /**
     * 查询文件是否都存在
     * @param request
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/selectIsFileExist")
    public SimpleCoreResponse selectIsFileExist( HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("123.xlsx","UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new AdscmSystemException("文件下载失败："+e.getMessage());
        }
        List<JyDrawingExcel> result=new ArrayList<>();
        String tokenId = request.getParameter("tokenId");
        Wrapper<JyDrawingList> wrapper=new EntityWrapper<>();
        wrapper.isNotNull("drawing_path");
        List<JyDrawingList> jyDrawingList = jyDrawingListService.selectList(wrapper);
        for (JyDrawingList drawingList : jyDrawingList) {

            if(AdscmBaseUtils.getInstance().isNotEmpty(drawingList.getDrawingPath(),null)){
                JyDrawingExcel jyDrawingExcel=new JyDrawingExcel();
                jyDrawingExcel.setId(drawingList.getId().toString());
                jyDrawingExcel.setName(drawingList.getDrawingName());

                File file =new File(formalUploadPath + drawingList.getDrawingPath());
                if (file.exists()){
                    jyDrawingExcel.setExist("1");

                }else {
                    jyDrawingExcel.setExist("0");
                }
                result.add(jyDrawingExcel);
            }
        }
        //指定文件输出位置
       // OutputStream outputStream =new FileOutputStream("F:/myexcel3.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcelFactory.getWriter(outputStream);
        //将要输出的内容填充到Sheet里
        Sheet sheet =new Sheet(1,0,JyDrawingExcel.class );
        //设置sheet表名
        sheet.setSheetName("my_three_excel");
        /**
         * 写数据到Write上下文中
         * 第一个参数：要写入的内容
         * 第二个参数：要写入的sheet目标
         */
        excelWriter.write(result,sheet);
        excelWriter.finish();
        outputStream.close();

        return new SimpleCoreResponse("200","查询成功" ,result);
    }


}

